package com.redis.dynamicthreadpool.config;

import com.redis.dynamicthreadpool.dynamic.DynamicThreadPoolExecutor;
import com.redis.dynamicthreadpool.properties.ThreadPoolProperties;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class ThreadPoolConfig {
    @Resource
    private ThreadPoolProperties threadPoolProperties;

    @Bean("threadPoolTaskExecutor")
    public DynamicThreadPoolExecutor threadPoolExecutor() {
        // 参数校验
        if (threadPoolProperties.getCorePoolSize() > threadPoolProperties.getMaximumPoolSize()) {
            throw new IllegalArgumentException("corePoolSize must be <= maximumPoolSize");
        }
        if (threadPoolProperties.getWorkQueueSize() < 0) {
            throw new IllegalArgumentException("workQueueSize must be non-negative");
        }

        return new DynamicThreadPoolExecutor(
                threadPoolProperties.getCorePoolSize(),
                threadPoolProperties.getMaximumPoolSize(),
                15L, // 显式指定long类型
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(threadPoolProperties.getWorkQueueSize()),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardPolicy()
        );
    }
}